// const baseUrl = 'http://localhost:3000'
import { getStorage } from './common';

interface HttpOptions {
  headers?: Record<string, string>;
  timeout?: number;
}

export default async function http<T>(
  url: string, 
  method: string, 
  data?: any, 
  options: HttpOptions = {}
): Promise<T> {
  const defaultHeaders = {
    'Content-Type': 'application/json',
    // 可以在这里添加其他默认headers，比如token
    'Authorization': `Bearer ${getStorage('token')}`
  }

  try {
    const response = await fetch(`${url}`, {
      method: method.toUpperCase(),
      headers: {
        ...defaultHeaders,
        ...options.headers
      },
      body: data ? JSON.stringify(data) : undefined,
      // 可以添加其他fetch选项
      credentials: 'include',  // 包含cookies
    })

    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 解析响应
    const result = await response.json()

    if (result.code === 200) {
      return result as T
    } else {
      alert(result.msg)
      throw new Error(result.msg)
    }

  } catch (error) {
    console.error('HTTP Request Failed:', error)
    throw error
  }
}
